<?php

namespace App\Http\Controllers\ZHIHU\Topics;

use DB;
use Config;
use Carbon\Carbon;
use App\Http\Controllers\ZHIHU\ApiController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;
use App\Validate\Zhihu\ZhihuValidator;
use App\Eloqumd\Zhihu\ZhihuAnswer;
use App\Eloqumd\Zhihu\ZhihuQuestion;
use App\Eloqumd\Zhihu\ZhihuAnswerAdopt;
use App\Eloqumd\Zhihu\ZhihuTopic;
use App\Eloqumd\Zhihu\ZhihuUser;
use App\Eloqumd\Zhihu\ZhihuFollower;
use App\Eloqumd\Zhihu\ZhihuVoteAnswer;
use App\Eloqumd\Zhihu\ZhihuFollowerQuestion;
use App\Eloqumd\Zhihu\ZhihuMessage;
use App\Eloqumd\Zhihu\ZhihuReportAnswer;
use App\Eloqumd\Zhihu\ZhihuUserPrestige;
use App\Eloqumd\Zhihu\ZhihuPrestige;
use App\Eloqumd\Zhihu\ZhihuCollection;
use App\Jobs\SystemMessagePublishedNotify;

class AnswersController extends ApiController
{
    // 获取问题及评论信息
    public function getQuestionCommentByQuestionID(Request $request)
    {
        $questionId = $request->input('question_id', 0);
        if (!$questionId) {
            return $this->jsonReturns(99999, trans('zhihu.Illegal-Parameter-Friend-No-Question'), null, 'verror');
        }

        // 处理阅读+1
        $key = 'VIEWQSS_' . $this->apiUser['id'] . '_' . $questionId;
        if (Redis::setnx($key, $key)) {
            Redis::setex($key, Config::get('api.zhihu_question_read'), $key);

            $questionModel = ZhihuQuestion::find($questionId);
            $questionModel->read_count = $questionModel->read_count + 1;
            $questionModel->save();
        }

        $question = ZhihuQuestion::find($questionId)->toArray();
        $topic = ZhihuTopic::find($question['topic_id']);
        $user = ZhihuUser::find($question['user_id']);
        
        $cate = Config::get('api.zhihu_question_type')[$question['cates']];
        
        if ($question['cates'] == 'blog') {
            $collection_count = ZhihuCollection::where('question_id', $questionId)->where('status', 1)->count();
            $question['meta'] = $topic->name . ' / ' . $cate . ' / 收藏(' . $collection_count . ') ' . ' / 阅读(' . $question['read_count'] . ') / 关注(' . $question['followers_count'] . ') / 喜欢(' . $question['favourite_count'] . ') / 评论(' . $question['answers_count'] . ')' . ' / ' . $question['created_at'];
        } else {
            $question['meta'] = $topic->name . ' / ' . $cate . ' / 阅读(' . $question['read_count'] . ') / 关注(' . $question['followers_count'] . ') / 喜欢(' . $question['favourite_count'] . ') / 评论(' . $question['answers_count'] . ')' . ' / ' . $question['created_at'];
        }
        
        $question['body'] = $question['content'];
        $question['lead'] = $question['lead'] == '' ? trans('zhihu.Question-Lead', [
            'title' => $question['title'],
            'username' => $user->nickname,
            'time' => $question['created_at']
        ]) : $question['lead'];

        // 评论信息
        $comment = ZhihuAnswer::where('question_id', $questionId)->where('status', 1)->orderBy('created_at', 'desc')->get()->toArray();
        foreach ($comment as $key => $val) {
            $user = ZhihuUser::find($val['user_id']);
            // dump($user);exit;
            $comment[$key]['body'] = $val['content'];
            $comment[$key]['avatar'] = empty($user['avatar']) ? Config::get('api.zhihu_default_img') : $user['avatar'];
            // $intro = is_null($user->settings) ? '' : (isset($user->settings['intro']) && !empty($user->settings['intro']) ? (' / ' . $user->settings['intro']) : '');
            // $comment[$key]['author'] = $user['nickname'] . ' / ' . $val['created_at'] . $intro;
            $comment[$key]['author'] = $user['nickname'] . ' / ' . time_trans($val['created_at']);

            // 是否关注用户
            $hasFollower = ZhihuFollower::where('follower_id', $this->apiUser['id'])->where('user_id', $val['user_id'])->where('status', 1)->count();
            $comment[$key]['hasFollower'] = $hasFollower;
            // 是否对答案点赞
            $hasVote = ZhihuVoteAnswer::where('answer_id', $val['id'])->where('user_id', $this->apiUser['id'])->where('status', 1)->count();
            $comment[$key]['hasVote'] = $hasVote;
            // 是否采纳
            $hasAdopt = ZhihuAnswerAdopt::where('answer_id', $val['id'])->where('question_id', $questionId)->count();
            $comment[$key]['hasAdopt'] = $hasAdopt;

            // 按钮权限
            $btn = [
                // 删除
                'delBtn' => 0,
                // 喜欢
                'voteBtn' => 1,
                // 采纳
                'adoptBtn' => 0,
                // 举报
                'reportBtn' => 0,
                // 关注评论用户
                'followeruserBtn' => 0,
                // 是否反转
                'reverse' => true,
            ];
            // 是否可以删除评论-只当评论为当前登录用户相同才为自己的
            if ($val['user_id'] == $this->apiUser['id']) {
                $btn['delBtn'] = 1;
                $btn['reverse'] = false;
            }
            // 当前问题为用户登录的自己的问题 并且 评论不是自己
            if ($this->apiUser['id'] == $question['user_id'] && $question['user_id'] != $val['user_id']) {
                $btn['adoptBtn'] = 1;
            }
            // 不是我的评论 && 当前评论用户不是自己
            if ($val['user_id'] != $this->apiUser['id']) {
                $btn['reportBtn'] = 1;
                $btn['followeruserBtn'] = 1;
            }

            $comment[$key]['authBtns'] = $btn;
        }

        $jsonData = [
            'questionData' => $question,
            'commentData' => $comment
        ];

        return $this->jsonReturns(10000, $this->success, $jsonData, 'get');
    }

    // 回答问题-评论
    public function answerQuestion(Request $request)
    {
        $param = $request->all();
        if (true !== $validateRes = ZhihuValidator::answerQuestion($param)) {
            return $this->jsonReturns(50000, $validateRes, null, 'verror');
        }

        DB::beginTransaction();
        try {
            $model = new ZhihuAnswer;
            $model->user_id = $this->apiUser['id'];
            $model->question_id = $param['question_id'];
            $model->content = $param['content'];
            $model->created_at = Carbon::now();
            $model->save();

            // 更新问题总数
            $question = ZhihuQuestion::find($param['question_id']);
            $question->answers_count = $question->answers_count + 1;
            $question->save();

            DB::commit();

            return $this->jsonReturns(10000, $this->success, null, 'comment');
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->jsonReturns(50000, $e->getMessage(), null, 'comment');
        }
    }

    // 删除回答问题-评论
    public function removeAnswerQuestion(Request $request)
    {
        $answerId = $request->input('id', 0);
        if (!$answerId) {
            return $this->jsonReturns(99999, trans('zhihu.Illegal-Parameter-Friend-No-Question'), null, 'verror');
        }

        DB::beginTransaction();
        try {
            $model = ZhihuAnswer::find($answerId);
            $model->status = 0;
            $model->removed_at = Carbon::now();
            $model->save();

            DB::commit();

            return $this->jsonReturns(10000, $this->success, null, 'delete');
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->jsonReturns(50000, $e->getMessage(), null, 'delete');
        }
    }

    // 我参与的问题-我评论过的问题
    public function myAnswerQuestionList(Request $request)
    {
        // ZhihuVoteAnswer
    }

    // 对回答的问题点赞-评论点赞
    public function answerQuestionVote(Request $request)
    {
        $answer_id = $request->input('answer_id', 0);
        if (!$answer_id) {
            return $this->jsonReturns(99999, trans('zhihu.The-ID-Can-Not-Be-Empty-Friend'), null, 'verror');
        }

        DB::beginTransaction();
        try {
            if (
                $model = ZhihuVoteAnswer::where('user_id', $this->apiUser['id'])
                    ->where('answer_id', $answer_id)
                    ->first()
            ) {
                $model->status = 1;
                $model->updated_at = Carbon::now();
            } else {
                $model = new ZhihuVoteAnswer;
            }

            $model->created_at = Carbon::now();
            $model->answer_id = $answer_id;
            $model->user_id = $this->apiUser['id'];
            $model->save();

            $asw = ZhihuAnswer::find($answer_id);
            $asw->votes_count = $asw->votes_count + 1;
            $asw->save();

            DB::commit();

            // 消息通知，以及socket
            $question = ZhihuQuestion::find($asw->question_id);
            $msg = new ZhihuMessage;
            $msg->from_id = $this->apiUser['systemId'];
            $msg->from_name = $this->apiUser['systemName'];
            $msg->to_id = (int)$asw->user_id;
            $msg->content = trans('zhihu.Vote-Answer-Notify', [
                'name' => $this->apiUser['nickname'],
                'title' => $question->title
            ]);
            // 用户
            $msg->status = 0;
            $msg->is_system = 1;
            $msg->created_at = Carbon::now();
            $msg->save();

            // socket通知
            $job = (new SystemMessagePublishedNotify([
                'channelType' => 'votes',
                'message' => $msg->content,
                'title' => trans('zhihu.System-Vote-Notify-Title'),
                'data' => $msg->toArray()
            ]));
            $this->dispatch($job);

            return $this->jsonReturns(10000, trans('zhihu.Votes-Success'), null, 'vote');
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->jsonReturns(50000, $e->getMessage(), null, 'vote');
        }
    }

    // 对回答的问题点赞-评论点赞-取消
    public function answerQuestionCancelVote(Request $request)
    {
        $answer_id = $request->input('answer_id', 0);
        if (!$answer_id) {
            return $this->jsonReturns(99999, trans('zhihu.The-ID-Can-Not-Be-Empty-Friend'), null, 'verror');
        }

        DB::beginTransaction();
        try {
            $model = ZhihuVoteAnswer::where('user_id', $this->apiUser['id'])
                ->where('answer_id', $answer_id)
                ->first();
            $model->status = 0;
            $model->updated_at = Carbon::now();
            $model->save();

            $asw = ZhihuAnswer::find($answer_id);
            $asw->votes_count = $asw->votes_count - 1;
            $asw->save();

            DB::commit();

            return $this->jsonReturns(10000, trans('zhihu.Votes-Cancel-Success'), null, 'votecancel');
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->jsonReturns(50000, $e->getMessage(), null, 'votecancel');
        }
    }

    // 对问题进行采纳
    public function answerQuestionAdopt(Request $request)
    {
        $answerId = $request->input('answer_id', 0);
        if (!$answerId) {
            return $this->jsonReturns(99999, trans('zhihu.The-ID-Can-Not-Be-Empty-Friend'), null, 'verror');
        }

        $asw = ZhihuAnswer::find($answerId);

        DB::beginTransaction();
        try {

            $model = new ZhihuAnswerAdopt;
            $model->answer_id = $answerId;
            $model->question_id = $asw->question_id;
            $model->user_id = $asw->user_id;
            $model->created_at = Carbon::now();
            $model->save();

            DB::commit();

            // 获取精华设置分值
            $score = (int)ZhihuPrestige::where('preskey', 'adopt')->where('status', 1)->value('score');

            $questionId = $asw->question_id;
            // 消息通知，以及socket
            $question = ZhihuQuestion::find($questionId);
            $msg = new ZhihuMessage;
            $msg->from_id = $this->apiUser['systemId'];
            $msg->from_name = $this->apiUser['systemName'];
            $msg->to_id = (int)$model->user_id;
            $msg->content = trans('zhihu.Adopt-Answer-Notify', [
                'name' => $this->apiUser['nickname'],
                'title' => $question->title,
                'score' => $score
            ]);
            $msg->status = 0;
            $msg->is_system = 1;
            $msg->created_at = Carbon::now();
            $msg->save();

            // socket通知
            $job = (new SystemMessagePublishedNotify([
                'channelType' => 'adopts',
                'message' => $msg->content,
                'title' => trans('zhihu.System-Adopt-Notify-Title'),
                'data' => $msg->toArray()
            ]));
            $this->dispatch($job);

            ZhihuUserPrestige::insert([
                'user_id' => $model->user_id,
                'title' => trans('zhihu.System-Answer-Beadopt-Title', [
                    'title' => $question->title,
                    'cate' => Config::get('api.zhihu_question_type')[$question->cates],
                ]),
                'conent' => trans('zhihu.System-Answer-Set-Adopt-Add-Score-Content', [
                    'name' => $this->apiUser['nickname'],
                    'title' => $question->title,
                    'cate' => Config::get('api.zhihu_question_type')[$question->cates],
                    'score' => $score,
                    'id' => $answerId
                ]),
                'types' => 0,
                'score' => $score,
                'created_at' => Carbon::now()
            ]);

            $message = [];
            $message['from_id'] = $this->apiUser['systemId'];
            $message['from_name'] = $this->apiUser['systemName'];
            $message['status'] = 0;
            $message['is_system'] = 1;
            $message['created_at'] = Carbon::now();
            $message['content'] = trans('zhihu.Adopt-Answer-Notify-The-Followers', [
                'name' => $this->apiUser['nickname'],
                'title' => $question->title
            ]);
            // 通知所有关注该问题的用户-通知该问题已经被采纳了
            $followerUsers = ZhihuFollowerQuestion::where('question_id', $questionId)->where('status', 1)->get()->toArray();
            foreach ($followerUsers as $k => $v) {
                // 消息发送及通知
                $message['to_id'] = (int)$v['user_id'];
                ZhihuMessage::insert($message);
                $job = (new SystemMessagePublishedNotify([
                    'channelType' => 'adopts',
                    'message' => $message['content'],
                    'title' => trans('zhihu.System-Adopt-Notify-Title'),
                    'data' => $message
                ]));
                $this->dispatch($job);
            }

            return $this->jsonReturns(10000, $this->success, null, 'adopt');
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->jsonReturns(50000, $e->getMessage(), null, 'adopt');
        }
    }

    // 举报答案
    public function reportAnswer(Request $request)
    {
        $param = $request->all();
        // 数据校验
        if (true !== $validateRes = ZhihuValidator::reportAnswer($param)) {
            return $this->jsonReturns(50000, $validateRes, null, 'verror');
        }

        $asw = ZhihuAnswer::find($param['answer_id']);
        $question = ZhihuQuestion::find($asw->question_id);

        DB::beginTransaction();
        try {
            $model = new ZhihuReportAnswer;

            $model->question_id = $asw->question_id;
            $model->question_title = $question->title;
            $model->answer_id = $param['answer_id'];
            $model->answer_user_id = $asw->user_id;
            $model->answer_content = $asw->content;
            $model->report_user_id = $this->apiUser['id'];
            $model->report_type = join(',', $param['report_type']);
            $model->report_descrption = $param['report_descrption'];
            $model->created_at = Carbon::now();
            $model->save();

            DB::commit();

            return $this->jsonReturns(10000, trans('zhihu.Report-Success'), null, 'report');
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->jsonReturns(50000, $e->getMessage(), null, 'report');
        }
    }
}
